<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <el-form ref="form" :model="order" :rules="rules" size="small" label-width="80px">
        <el-row :gutter="10">
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="单据编码">
              <el-input v-model="order.code" placeholder="自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="日期 ">
              <el-date-picker
                v-model="order.busDate"
                type="date"
                value-format="yyyy-MM-dd"
                :disabled="order.orderStatus==='PASS'|| order.orderStatus==='CLOSE'"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="客户名称" prop="customerId">
              <div class="flex flex-row">
                <el-input
                  v-model="order.customerCode"
                  disabled
                  style="width: 30%;"
                />
                <zSelect
                  :disabled="order.orderStatus==='PASS'|| order.orderStatus==='CLOSE' || (isDept && !order.deptId)"
                  ref="selectCustomer"
                  :value.sync="order.customerId"
                  :label="order.customerName"
                  :showName="order.customerName"
                  @getChange="getInfo"
                  url="api/dropDown/basCustomerList"
                  style="width: 70%;"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="单据状态">
              <v-select
                v-model="order.orderStatus"
                :options="dict.common_order_status"
                disabled
                class="edit-input"
                placeholder="单据状态"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="核销状态">
              <v-select
                v-model="order.cancelStatus"
                :options="dict.common_cancel_status"
                disabled
                class="edit-input"
                placeholder="请选择核销状态"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="业务员">
              <zSelect
                :value.sync="order.userId"
                :showName="order.userName"
                :label="order.userName"
                :disabled="order.orderStatus==='PASS'|| order.orderStatus==='CLOSE'"
                url="api/dropDown/sysUserList"
                style="width: 100%;"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="部门">
              <z-select
                :value.sync="order.deptId"
                :showName="order.deptName"
                :disabled="order.orderStatus==='PASS'|| order.orderStatus==='CLOSE'"
                url="api/dropDown/childSysDeptList"
                style="width:  100%"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="联系人">
              <el-input
                v-model="order.contactName"
                :disabled="order.orderStatus==='PASS'|| order.orderStatus==='CLOSE'"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="联系电话">
              <el-input
                v-model="order.contactPhone"
                :disabled="order.orderStatus==='PASS' || order.orderStatus==='CLOSE'"
                placeholder="请输入"
                maxlength="11"
                oninput="value=value.replace(/[^\d]/g,'')"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="所属商贸">
              <zSelect
                :value.sync="order.fCustomerId"
                :disabled="order.orderStatus==='PASS'|| order.orderStatus==='CLOSE'"
                url="api/dropDown/fCustomerList"
                :params="{ids:order.customerId}"
                :show-name="order.fCustomerName"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="所属二批">
              <zSelect
                :value.sync="order.sCustomerId"
                :disabled="order.orderStatus==='PASS'|| order.orderStatus==='CLOSE'"
                url="/api/dropDown/sCustomerList"
                :params="{ids:order.customerId}"
                :show-name="order.sCustomerName"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
            <el-form-item label="备注">
              <el-input v-model="order.remark" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <crudOperation :permission="permission" :show-right="false">
        <el-button
          slot="left"
          v-permission="permission.addDetail"
          class="filter-item"
          size="mini"
          type="primary"
          @click="toAdd"
        >
          添加
        </el-button>
        <el-button
          slot="left"
          v-permission="permission.add"
          class="filter-item"
          size="mini"
          type="primary"
          @click="addOrSave"
        >
          保存
        </el-button>
        <el-button
          slot="left"
          v-permission="permission.pass"
          :disabled="/(copy)/g.test(this.$route.params.id)"
          class="filter-item"
          size="mini"
          type="success"
          @click="passOrReject('PASS')"
        >
          审核
        </el-button>
        <el-button
          slot="left"
          v-permission="permission.reject"
          :disabled="/(copy)/g.test(this.$route.params.id)"
          class="filter-item"
          size="mini"
          type="danger"
          @click="passOrReject('REJECT')"
        >
          反审
        </el-button>
        <el-button
          slot="left"
          v-permission="permission.copy"
          class="filter-item"
          size="mini"
          type="warning"
          :disabled="$route.params.id == 'add'"
          @click="toCopy"
        >
          复制
        </el-button>
        <el-button
          slot="left"
          v-permission="permission.del"
          :disabled="crud.selections.length === 0"
          :loading="crud.delAllLoading"
          class="filter-item"
          size="mini"
          type="danger"
          @click="toDel"
        >
          删除
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="warning"
          @click="printIsSave"
        >
          打印
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView1"
        >
          打印预览
        </el-button>
        <el-button
          slot="right"
          icon="el-icon-refresh"
          size="mini"
          @click="detail"
          style="vertical-align: top"
        />
      </crudOperation>
      <!--打印模板-->
      <el-dialog
        title="请选择打印模板"
        :visible.sync="crud.printConfig.pringDialog"
        width="30%"
      >
        <jPrintConfig
          groupId="orderMeeting"
          v-if="crud.printConfig.pringDialog"
          @getPrintId="crud.toPrint"
          :isPreview="crud.printConfig.isPreview"
        />
      </el-dialog>
      <!--打印预览-->
      <el-dialog
        title="打印预览"
        destroy-on-close
        v-dialogDrag
        close-on-press-escape
        :visible.sync="showPdf"
        append-to-body width="50vw"
      >
        <j-pdf :src="pdfSrc" />
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        stripe
        border
        v-loading="tableLoading"
        :data="content"
        size="small"
        style="width: 100%;"
        show-summary
        :summary-method="crud.sumRow"
        @selection-change="crud.selectionChangeHandler"
        @row-contextmenu="rowContextmenu"
        @header-contextmenu="headerContextmenu"
        @row-dblclick="rowDblclick"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="55" label="序号" />
        <el-table-column
          v-if="item.visible"
          v-for="(item, index) in header"
          :key="`col_${index}`"
          :prop="item.prop"
          :label="columnLabel(item)"
          :width="item.width + 'px'"
          :data-porp='item.prop'
          @header-dragend="changeColWidth"
          :fixed="item.fixed"
          :sortable="item.sortable?'custom':false"
          :sort-orders="['descending', 'ascending', null]"
          sort-change="sort"
        >

          <template slot-scope="scope">
            <div v-if="item.type==1" :class="{red:order.type == 2}">
              <div v-if="order.type === 2">
                <div v-if="red.includes(item.prop)">
                  -{{ scope.row[`${item.prop}`] }}
                </div>
                <div v-else>{{ scope.row[`${item.prop}`] }}</div>
              </div>
              <div v-else>
                {{ scope.row[`${item.prop}`] }}
              </div>
            </div>
            <div v-else-if="item.type==2" :class="{red:order.type == 2}">
              {{ scope.row[`${item.prop}`] | parseTime }}
            </div>
            <div v-else-if="item.type==3" :class="{red:order.type == 2}">
              {{ getDict(`this.dict.label.${item.dictionary}["${scope.row[item.prop]}"]`) }}
            </div>
            <div v-else-if="item.type==4" :class="{red:order.type == 2}">
              <template v-if="item.prop=='goodsName'">
                <div
                  v-if="(order.orderStatus==='PASS' || order.orderStatus==='CLOSE') && scope.row.id">
                  {{ scope.row.goodsName }}
                </div>
                <el-input
                  v-else
                  v-model="scope.row.goodsName"
                  placeholder="请输入商品"
                  @keyup.enter.native="onKeyupEnter(scope.$index, scope.row.goodsName)"
                />
              </template>
              <!--数量-->
              <template v-if="item.prop=='goodsCount'">
                <el-input
                  v-if="scope.row.edit"
                  v-model="scope.row.goodsCount"
                  style="width: 100%;float: left;"
                  @input="couputedGoodsUnitCount(scope.row)"
                  @change="changGoodsCount(scope.row)"
                />
                <div v-else>{{ scope.row.goodsCount }}</div>
              </template>
              <!--箱数-->
              <template v-if="item.prop=='boxCount'">
                <el-input
                  v-if="scope.row.edit"
                  v-model="scope.row.boxCount"
                  placeholder="请输入内容"
                />
                <div v-else>{{ scope.row.boxCount }}</div>
              </template>
              <!--箱单位数量-->
              <template v-if="item.prop=='boxNum'">
                <div v-if="scope.row.edit">
                  <el-input
                    v-model="scope.row.boxNum"
                    @input="crud.inuptCount(scope, 'boxNum')"
                    @change="changGoodsCount(scope.row)"
                    style="width: 50%;float: left;"
                  >
                    <template slot="append">{{ scope.row.boxUnitName }}</template>
                  </el-input>
                  <el-input
                    v-model="scope.row.mainNum"
                    @input="crud.inuptCount(scope, 'mainNum')"
                    @change="changGoodsCount(scope.row)"
                    style="width: 50%;float: left;"
                  >
                    <template slot="append">{{ scope.row.mainUnitName }}</template>
                  </el-input>
                </div>
                <div v-else>
                  <span>{{ scope.row.boxNum }}{{ scope.row.boxUnitName }}</span>
                  <span>{{ scope.row.mainNum }}{{ scope.row.mainUnitName }}</span>
                </div>
              </template>
              <template v-if="item.prop=='taxPrice'">
                <el-input
                  v-if="scope.row.edit"
                  oninput="value=value.replace(/[^\d^\.]/g,'')"
                  maxlength="12"
                  @input="crud.inuptCount(scope, 'taxPrice')"
                  v-model="scope.row.taxPrice"
                  placeholder="请输入内容"
                />
                <div v-else>{{ scope.row.taxPrice }}</div>
              </template>
              <template v-if="item.prop=='taxBoxPrice'">
                <el-input
                  v-if="scope.row.edit"
                  oninput="value=value.replace(/[^\d^\.]/g,'')"
                  maxlength="12"
                  @input="crud.inuptCount(scope, 'taxBoxPrice')"
                  v-model="scope.row.taxBoxPrice"
                  placeholder="请输入内容"
                />
                <div v-else>{{ scope.row.taxBoxPrice }}</div>
              </template>
              <template v-if="item.prop=='taxAmount'">
                <el-input
                  v-if="scope.row.edit"
                  oninput="value=value.replace(/[^\d^\.]/g,'')"
                  maxlength="12"
                  @input="crud.inuptCount(scope, 'taxAmount')"
                  v-model="scope.row.taxAmount"
                  placeholder="请输入内容"
                />
                <div v-else>{{ scope.row.taxAmount }}</div>
              </template>
              <template v-if="item.prop=='goodsTagName'">
                <zSelect
                  v-if="scope.row.edit"
                  :value.sync="scope.row.goodsTagId"
                  :params="{sort:'code asc'}"
                  :showName="scope.row.goodsTagName"
                  :label="scope.row.goodsTagName"
                  placeholder="请输入内容"
                  @change="crud.setProduct($event, scope, 'goodsTagName')"
                  url="api/dropDown/basGoodsTagList"
                  style="width: 100%;"
                />
                <div v-else>{{ scope.row.goodsTagName }}</div>
              </template>
              <template v-if="item.prop=='detailRemark'">
                <el-input
                  v-if="scope.row.edit"
                  v-model="scope.row.detailRemark"
                  placeholder="请输入内容"
                />
                <div v-else>{{ scope.row.detailRemark }}</div>
              </template>
              <template v-if="item.prop=='noTaxPrice'">
                <div>{{ scope.row.noTaxPrice }}</div>
              </template>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--表格配置-->
    <el-dialog
      title="表格配置"
      :visible.sync="tableConfigShow"
      width="60%"
    >
      <j-table-column-config :columns.sync="header" :headerInfo="headerInfo" @tabSave="saveHead" />
    </el-dialog>
    <!--选择商品-->
    <el-dialog
      title="选择商品"
      :visible.sync="showQueryGoods"
      width="80%"
      @close="showQueryGoods=false"
    >
      <v-goods-picker
        v-if="showQueryGoods"
        url="api/dropDown/basGoodsListForAdd"
        :params="{customerId:order.customerId,keyword:goodsName,type:'SALE'}"
        @confirm="tablePickerChange"
        @cancel="showQueryGoods=false"
      />
    </el-dialog>
    <vue-context-menu
      :contextMenuData="contextMenuData"
      @tableConfig="tableConfig"
      @del="delRow"
      @add="addRow"
    />
  </div>
</template>

<script>
import crudOrderMeeting from '@/api/erp/orderMeeting'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import jPrintConfig from '@/components/jPrintConfig/jPrintConfig'
import VGoodsPicker from '@/components/VGoodsPicker'
import VSelect from '@/components/VSelect'
import jTableColumnConfig from '@/components/jTableColumnConfig/jTableColumnConfig'
import { get as getDictDetail } from '@/api/system/dictDetail'
import { pdfmixins } from '@/mixins/pdfmixins'
import { tablemixins } from './tablemixins'

// crud交由presenter持有
const defaultCrud = CRUD({
  title: '订货会明细',
  url: 'api/orderMeeting/detail',
  name: 'orderMeetingDetail',
  sort: 't.seq,asc',
  crudMethod: { ...crudOrderMeeting },
  optShow: {
    isShow: true,
    add: false,
    edit: false,
    del: false,
    download: false,
    leadingIn: false,
    enable: false,
    disable: false,
    pass: false,
    reject: false,
    copy: false,
    downloadDetail: false,
    recover: false,
    invalid: false,
    print: false, // 打印
    printDetail: false, // 打印详情
    unAccept: false, // 反验收
    accept: false // 验收
  }
})
const defaultForm = {
  id: null,
  busdate: new Date(),
  code: null,
  customerId: null,
  customerCode: null,
  customerName: null,
  customerAreaId: null,
  customerAreaCode: null,
  customerAreaName: null,
  customerTypeId: null,
  customerTypeCode: null,
  customerTypeName: null,
  userId: null,
  userCode: null,
  userName: null,
  deptId: null,
  deptCode: null,
  deptName: null,
  orderStatus: null,
  boxCount: null,
  count: null,
  taxAmount: null,
  noTaxAmount: null,
  tax: null,
  cancelStatus: null,
  unCancelAmount: null,
  cancelAmount: null,
  remark: null,
  contactName: null,
  contactPhone: null,
  sCustomerId: null,
  sCustomerCode: null,
  sCustomerName: null,
  isPrint: null,
  printCount: null,
  createUserId: null,
  createUserCode: null,
  createUserName: null,
  createTime: null,
  updateUserId: null,
  updateUserCode: null,
  updateUserName: null,
  updateTime: null,
  auditUserId: null,
  auditUserCode: null,
  auditUserName: null,
  auditTime: null,
  closeUserId: null,
  closeUserCode: null,
  closeUserName: null,
  closeTime: null,
  cancelUserId: null,
  cancelUserCode: null,
  cancelUserName: null,
  cancelDate: null
}
export default {
  name: 'orderMeetingDetail',
  components: { crudOperation, rrOperation, udOperation, jPrintConfig, VGoodsPicker, VSelect, jTableColumnConfig },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud(), pdfmixins, tablemixins],
  dicts: ['common_order_status', 'common_cancel_status', 't_sales_order_save_order_status_is_allow_print'],
  data() {
    return {
      permission: {
        add: ['admin', 'orderMeeting:add'],
        edit: ['admin', 'orderMeeting:edit'],
        del: ['admin', 'orderMeeting:del'],
        import: ['admin', 'orderMeeting:import'],
        export: ['admin', 'orderMeeting:export'],
        copy: ['admin', 'orderMeeting:copy'],
        upload: ['admin', 'orderMeeting:upload'],
        download: ['admin', 'orderMeeting:download'],
        pass: ['admin', 'orderMeeting:pass'],
        reject: ['admin', 'orderMeeting:reject'],
        closed: ['admin', 'orderMeeting:closed'],
        invalid: ['admin', 'orderMeeting:invalid'],
        stop: ['admin', 'orderMeeting:stop'],
        recover: ['admin', 'orderMeeting:recover']
      },
      rules: {
        customerId: [
          { required: true, message: '客户id不能为空', trigger: 'blur' }
        ]
      },
      isDept: false,
      customerParams: {
        sort: 'code,asc'
      },
      tableLoading: false,
      content: [],
      header: [],
      order: Object.assign({}, defaultForm),
      summary: {},
      contextmenu: false,
      currentRow: null,
      showQueryGoods: false,
      user: {},
      red: ['goodsCount', 'boxCount', 'taxAmount', 'noTaxAmount', 'tax', 'discountAmount', 'acceptGoodsCount', 'acceptBoxCount', 'oldTaxAmount', 'oldNoTaxAmount', 'oldTax', 'acceptTaxAmount', 'acceptNoTaxAmount', 'acceptTax', 'boxNum', 'mainNum', 'acceptBoxNum', 'acceptMainNum', 'cancelAmount', 'unCancelAmount'],
      contextMenuData: {
        menuName: 'table',
        axis: {
          x: null,
          y: null
        },
        menulists: [
          {
            fnHandler: 'tableConfig', // 绑定事件
            icoName: 'el-icon-setting', // icon图标
            btnName: '表格设置' // 菜单名称
          },
          {
            fnHandler: 'add', // 绑定事件
            icoName: 'el-icon-edit', // icon图标
            btnName: '新增' // 菜单名称
          },
          {
            fnHandler: 'del', // 绑定事件
            icoName: 'el-icon-edit', // icon图标
            btnName: '删除' // 菜单名称
          }
        ]
      },
      goodsName: '',
      rowIndex: 0
    }
  },
  created() {
    this.user = this.$store.state.user.user
    this.headerInfo = {
      name: 'orderMeetingDetail',
      code: 'orderMeetingDetail',
      path: 'api/orderMeeting/detail',
      userId: this.user.userId
    }
    this.getHead()
  },
  activated() {
    if (/(add)/g.test(this.$route.params.id)) {
      this.orderInit()
    }
    if (/(copy)/g.test(this.$route.params.id)) {
      this.order.orderStatus = 'SAVE'
    }
    this.detail()
  },
  methods: {
    orderInit() {
      getDictDetail('t_sales_order_customer_is_follow_login_user_dept').then(res => {
        if (res.data.content[0].value === '1') {
          this.isDept = true
          if (this.user.deptId === 0) {
            this.$message.error('登录用户未配置部门，请先选择部门')
            return
          }
          this.order.deptId = this.user.deptId
          this.order.deptName = this.user.deptName
          if (!this.order.customerId)
            this.$refs.selectCustomer.$el.getElementsByTagName('input')[0].focus()
        } else {
          this.$refs.selectCustomer.$el.getElementsByTagName('input')[0].focus()
        }
      })
    },
    detail() {
      const id = this.$route.query.copyId || this.$route.params.id
      if (id === 'add') {
        return
      }
      this.tableLoading = true
      crudOrderMeeting.detail({ id, page: 0, size: 999, sort: 't.seq,asc' }).then(res => {
        this.content = res.data.content.map(item => {
          this.$set(item, 'edit', false)
          if (/(copy)/g.test(this.$route.params.id)) {
            this.$set(item, 'id', null)
          }
          return item
        })
        this.order = res.data.order

        if (/(copy)/g.test(this.$route.params.id)) {
          this.order.code = null
          this.order.orderStatus = null
        }
        this.summary = res.data.summary
        this.tableLoading = false
        this.crud.loadingClose()
      }).catch(() => {
        this.tableLoading = false
        this.crud.loadingClose()
      })
    },
    addOrSave() {
      if (!this.order.customerId) {
        this.$message({
          message: '请先选择客户',
          type: 'error'
        })
        return
      }
      if (this.content.some(item => !item.goodsCount)) {
        this.$message.error('存在数量为0的商品')
        return
      }
      this.$refs.form.validate((valid) => {
        if (valid) {
          const flag = /(add|copy)/g.test(this.$route.params.id)
          // 新增、复制 需删除id
          flag && delete this.order.id
          // 新增或编辑
          const actionName = flag ? crudOrderMeeting.add : crudOrderMeeting.edit
          // 组装入参
          const data = {
            ...this.order,
            detailList: this.content
          }
          console.log(data)
          this.crud.loadingOpen()
          actionName(data).then(res => {
            if (flag) {
              this.$router.replace('/redirect/sale/orderMeetingDetail/' + res.data.id)
            } else {
              this.crud.loadingClose()
              this.$message.success('保存成功')
              this.detail()
            }
          }).catch(() => {
            this.crud.loadingClose()
            this.$message.error('修改失败，稍后再试')
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    passOrReject(type) {
      const id = this.$route.query.copyId || this.$route.params.id
      const data = {
        ids: [id],
        type
      }
      this.crud.loadingOpen()
      crudOrderMeeting.passOrReject(data).then(() => {
        this.crud.loadingClose()
        this.$message.success('操作成功')
        this.detail()
      }).catch(() => {
        this.crud.loadingClose()
        this.$message.error('修改失败，稍后再试')
      })
    },
    printIsSave() {
      for (let i of this.crud.selections) {
        if (this.dict.t_sales_order_save_order_status_is_allow_print[0].value == '0' && i.orderStatus === 'SAVE') {
          this.$message.error('保存状态单据不允许打印')
          return
        } else if (i.isPrint == '1') {
          this.$message.error(`单据${i.code}已打印`)
          return
        }
      }
      this.crud.preView()
      setTimeout(() => {
        this.detail()
      }, 6000)
    },
    getInfo(e) {
      this.order.customerCode = e.code
      this.order.warehouseId = e.warehouseId
      this.order.customerAreaName = e.customerAreaName
      this.order.customerAreaId = e.customerAreaId
      this.order.deptId = e.deptId
      this.order.deptName = e.deptName
      this.order.userId = e.userId
      this.order.userName = e.userName
      this.order.scustomerid = null
      this.sCustomerList = e.scustomerList
      this.order.carId = e.carId
      this.order.customerTypeId = e.customerTypeId
      this.order.loadCode = e.loadCode
      this.order.loadTime = e.loadTime
      this.order.driverUserId = e.driverUserId
      this.order.followUserId = e.followUserId
      this.order.printStatus = e.printStatus
      this.order.verifyCode = e.verifyCode
      this.order.remark = e.remark
      this.order.usableNum = e.usableNum
      this.order.printCount = e.printCount
      this.order.acceptStatus = e.acceptStatus
      this.order.cancelStatus = e.cancelStatus
      this.order.pickSeq = e.pickSeq
      this.order.warehouseId = e.warehouseId
      this.order.warehouseName = e.warehouseName
      this.order.contactName = e.contactName
      this.order.contactPhone = e.contactPhone
      this.order.deliveryAddress = e.deliveryAddress
      this.order.address = e.address
      try {
        if (e.scustomerList || e.scustomerList.lenght === 1) {
          this.order.scustomerId = e.scustomerList[0].scustomerId
          this.order.scustomerName = e.scustomerList[0].scustomerName
        } else {
          this.order.scustomerId = null
          this.order.scustomerName = null
          console.log('设置成功')
        }
      } catch (e) {
        this.order.scustomerId = null
        this.order.scustomerName = null
      }
      if (this.content.length === 0) {
        this.content.push({
          isSelected: true,
          id: null,
          code: null,
          name: null,
          type: null,
          saleType: 1,
          busDate: null,
          sourceType: null,
          sourceId: null,
          sourceCode: null,
          serialNumber: null,
          customerOrderCode: null,
          customerId: null,
          customerCode: null,
          customerName: null,
          isContact: 1,
          deptId: [],
          deptCode: null,
          deptName: null,
          userId: null,
          userCode: null,
          userName: null,
          warehouseId: null,
          warehouseCode: null,
          warehouseName: null,
          count: null,
          boxCount: null,
          taxAmount: null,
          noTaxAmount: null,
          tax: null,
          discountAmount: null,
          acceptBoxCount: null,
          acceptTaxAmount: null,
          acceptNoTaxAmount: null,
          acceptTax: null,
          cancelAmount: null,
          unCancelAmount: null,
          receiveDate: null,
          carId: null,
          carCode: null,
          carName: null,
          loadId: null,
          loadCode: null,
          loadTime: null,
          driverUserId: null,
          driverUserCode: null,
          driverUserName: null,
          followUserId: null,
          followUserIds: null,
          followUserCode: null,
          followUserName: null,
          printStatus: null,
          printCount: null,
          customerAreaId: null,
          customerAreaCode: null,
          customerAreaName: null,
          customerTypeId: null,
          customerTypeCode: null,
          customerTypeName: null,
          pCustomerId: null,
          pCustomerCode: null,
          pCustomerName: null,
          mCustomerId: null,
          mCustomerCode: null,
          mCustomerName: null,
          sCustomerId: null,
          sCustomerCode: null,
          sCustomerName: null,
          seq: null,
          orderStatus: null,
          acceptStatus: 0,
          cancelStatus: null,
          remark: null,
          orderRemark: null,
          createUserId: null,
          createUserCode: null,
          createUserName: null,
          createTime: null,
          updateUserId: null,
          updateUserCode: null,
          updateUserName: null,
          updateTime: null,
          closeUserId: null,
          closeUserCode: null,
          closeUserName: null,
          closeTime: null,
          billTaxPrice: null,
          billTaxBoxPrice: null,
          usableNum: null,
          billTaxAmount: null,
          locationId: null,
          locationName: null,
          goodsName: null
        })
        this.rowIndex = 0
        setTimeout(() => {
          this.$refs.table.setCurrentRow(this.crud.data[0])
          const list = this.$refs.table.$el.querySelectorAll('.el-table__body tr')[0].querySelectorAll('.el-input__inner,.el-textarea__inner')
          list[0].focus()
        }, 10)
      }
    },
    changGoodsCount(row) {
      if (row.isOne === 1) {
        const promotionData = JSON.parse(row.promotionData)
        const gift = promotionData.gift
        const ruleList = promotionData.ruleList
        const giftCount = this.getGiftCount(row, gift, ruleList)
        const num = Number(giftCount.match(/\d+/)[0])
        const unitName = giftCount.match(/\D+/)[0]
        if (num === 0) {
          const dataList = this.content.filter(item => item.promotionGroupKey == row.promotionGroupKey && item !== row)
          const delList = []
          dataList.forEach(item => {
            const index = this.content.findIndex(val => val === item)
            const id = this.content[index].id
            id && delList.push(id)
            this.content.splice(index, 1)
          })
          this.$message.error('删除赠品后请及时保存')
          this.delRows(delList)
        } else {
          const giftData = this.content.find(item => item.promotionGroupKey == row.promotionGroupKey && item.isGift == '1')
          if (giftData) {
            if (unitName === '箱') {
              giftData.boxNum = num
              giftData.goodsCount = giftData.boxNum * Number(giftData.boxUnitCount)
            } else {
              giftData.goodsCount = num
              giftData.boxNum = parseInt(giftData.goodsCount / Number(giftData.boxUnitCount))
              giftData.mainNum = giftData.goodsCount % Number(giftData.boxUnitCount)
            }
            const emptyBox = this.content.find(item => item.promotionEmptyBoxKey == gift.promotionEmptyBoxKey && item.isEmptyBoxAdd == '1')
            if (emptyBox) {
              emptyBox.boxNum = Number(giftData.boxNum)
              emptyBox.mainNum = 0
              emptyBox.goodsCount = emptyBox.boxNum
              emptyBox.billTaxPrice = emptyBox.billTaxPrice || emptyBox.taxPrice
              emptyBox.billTaxBoxPrice = emptyBox.billTaxBoxPrice || emptyBox.taxBoxPrice
              emptyBox.taxAmount = emptyBox.goodsCount * emptyBox.taxPrice
              emptyBox.billTaxAmount = emptyBox.billTaxPrice * emptyBox.goodsCount
              emptyBox.boxCount = emptyBox.boxNum
            } else {
              const emptyBox = promotionData.emptyBox
              emptyBox.boxNum = Number(giftData.boxNum)
              emptyBox.mainNum = 0
              emptyBox.goodsCount = emptyBox.boxNum
              emptyBox.billTaxPrice = emptyBox.billTaxPrice || emptyBox.taxPrice
              emptyBox.billTaxBoxPrice = emptyBox.billTaxBoxPrice || emptyBox.taxBoxPrice
              emptyBox.taxAmount = emptyBox.goodsCount * emptyBox.taxPrice
              emptyBox.billTaxAmount = emptyBox.billTaxPrice * emptyBox.goodsCount
              emptyBox.boxCount = emptyBox.boxNum
              const index = this.content.findIndex(item => item == gift)
              this.content.splice(index + 1, 0, emptyBox)
            }
          } else {
            const giftData = Object.assign({}, gift)
            if (unitName === '箱') {
              giftData.boxNum = num
              giftData.goodsCount = giftData.boxNum * Number(giftData.boxUnitCount)
            } else {
              giftData.goodsCount = num
              giftData.boxNum = parseInt(giftData.goodsCount / Number(giftData.boxUnitCount))
              giftData.mainNum = giftData.goodsCount % Number(giftData.boxUnitCount)
            }
            const index = this.content.findIndex(item => item === row)
            this.content.splice(index + 1, 0, giftData)
            const emptyBox = this.content.find(item => item.promotionEmptyBoxKey == row.promotionEmptyBoxKey && item.isEmptyBoxAdd == '1')
            if (emptyBox) {
              emptyBox.boxNum = Number(giftData.boxNum)
              emptyBox.mainNum = 0
              emptyBox.goodsCount = emptyBox.boxNum
              emptyBox.billTaxPrice = emptyBox.billTaxPrice || emptyBox.taxPrice
              emptyBox.billTaxBoxPrice = emptyBox.billTaxBoxPrice || emptyBox.taxBoxPrice
              emptyBox.taxAmount = emptyBox.goodsCount * emptyBox.taxPrice
              emptyBox.billTaxAmount = emptyBox.billTaxPrice * emptyBox.goodsCount
              emptyBox.boxCount = emptyBox.boxNum
            } else {
              const emptyBox = promotionData.emptyBox
              emptyBox.boxNum = Number(giftData.boxNum)
              emptyBox.mainNum = 0
              emptyBox.goodsCount = emptyBox.boxNum
              emptyBox.billTaxPrice = emptyBox.billTaxPrice || emptyBox.taxPrice
              emptyBox.billTaxBoxPrice = emptyBox.billTaxBoxPrice || emptyBox.taxBoxPrice
              emptyBox.taxAmount = emptyBox.goodsCount * emptyBox.taxPrice
              emptyBox.billTaxAmount = emptyBox.billTaxPrice * emptyBox.goodsCount
              emptyBox.boxCount = emptyBox.boxNum
              const index = this.content.findIndex(item => item === giftData)
              this.content.splice(index + 1, 0, emptyBox)
            }
          }
        }
      }
      if (row.giftId && row.goodsCount > row.unGiftGoodsCount) {
        this.$message({
          message: '下单数量不可大于可下单数量',
          type: 'error'
        })
        row.boxNum = 0
        row.mainNum = 0
        row.goodsCount = 0
      }
    },
    couputedGoodsUnitCount(row) {
      //判断是否满足最小销售单位和退货单位
      if (row.boxUnitCount > 0) {
        row.boxNum = parseInt(row.goodsCount / row.boxUnitCount)
      }
      if (row.mainUnitCount > 0) {
        row.mainNum = parseInt((row.goodsCount - row.boxUnitCount * row.boxNum) / row.mainUnitCount)
      }
      if (row.minSaleUnitCount && this.form.type == 1 && row.minSaleUnitCount > 0) {
        if (row.goodsCount % row.mainUnitCount != 0) {
          //不满足
          this.$message.error('请输入最小销售单位' + row.minSaleUnitCount + '整数倍的数量')
          return false
        }
      }
      if (row.minReturnUnitCount && this.form.type == 2 && row.minReturnUnitCount > 0) {
        if (row.goodsCount % row.mainUnitCount != 0) {
          //不满足
          this.$message.error('请输入最小退货单位' + row.minReturnUnitCount + '整数倍的数量')
          return false
        }
      }
      this.computedMoney(row)
    },
    computedMoney(row) {
      //计算价格
      row.noTaxAmount = this.formatNum(row.noTaxBoxPrice * row.boxNum + row.noTaxPrice * row.mainNum)
      row.taxAmount = this.formatNum(row.taxBoxPrice * row.boxNum + row.taxPrice * row.mainNum)

      row.billTaxAmount = Number(row.billTaxPrice) * Number(row.goodsCount)
      // this.calcuForm() //计算form参数
      this.$forceUpdate()
    },
    formatNum: function (num, n = 6) {
      n = n ? parseInt(n) : 0
      if (n <= 0) {
        return Math.round(num)
      }
      num = Math.round(num * Math.pow(10, n)) / Math.pow(10, n) //四舍五入
      num = Number(num).toFixed(n) //补足位数
      return num
    },
    toCopy() {
      const id = this.$route.query.copyId || this.$route.params.id
      this.$router.push({
        path: `/redirect/sale/orderMeetingDetail/copy${new Date().getTime()}`,
        query: { copyId: id }
      })
    },
    toDel() {
      const selectCount = this.crud.selections.length
      console.log(this.crud.selections)
      this.$confirm(`此操作将直接删除${selectCount || 0}条产品记录, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = []
        this.crud.selections.forEach(item => {
          if (item.id) {
            ids.push(item.id)
          }
          const index = this.content.findIndex(ktem => ktem.goodsId === item.goodsId)
          this.$delete(this.content, index)
        })
        if (ids.length) {
          crudOrderMeeting.deleteDetail(ids).then((res) => {
            this.detail()
          })
        }
      })
    },
    toAdd() {
      if (!this.order.customerId) {
        this.$message.error('请先选择客户')
        return
      }
      if (this.order.isAccept === 1) {
        this.$message.error('已验收不允许新增')
        return
      }
      this.content.push(Object.assign({}, { edit: true }))
      this.rowIndex = this.content.length - 1
      this.goodsName = ''
      this.showQueryGoods = true
    },
    rowContextmenu(row, column, event) {
      this.currentRow = null
      if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
        return
      }
      event.preventDefault()
      var x = event.clientX
      var y = event.clientY
      // Get the current location
      this.contextMenuData.axis = {
        x, y
      }
      this.currentRow = row
    },
    headerContextmenu(column, event) {
      if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
        return
      }
      event.preventDefault()
      var x = event.clientX
      var y = event.clientY
      // Get the current location
      this.contextMenuData.axis = {
        x, y
      }
    },
    onKeyupEnter(index, val) {
      this.rowIndex = index
      this.goodsName = val
      this.showQueryGoods = true
    },
    rowDblclick(row, column, event) {
      row.edit = !row.edit
    },
    addRow() {
      if (this.order.orderStatus === 'SAVE' || this.order.orderStatus === null) {
        this.toAdd()
        return
      }
      this.$message.error('非保存单据不能添加')
    },
    delRow() {
      const index = this.content.findIndex(item => item.id === this.currentRow.id)
      if (this.currentRow.id) {
        this.$confirm('此操作将直接删除此条产品记录, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          crudOrderMeeting.deleteDetail([this.currentRow.id]).then(res => {
            this.$delete(this.content, index)
            this.$message.success('删除成功')
            this.detail()
          })
        }).catch(() => {
        })
      } else {
        this.content.splice(index, 1)
      }
    },
    tablePickerChange(val) {
      this.$set(this.content, this.rowIndex, { ...val, edit: true })
      this.showQueryGoods = false
    },
    // 获取数据前设置好接口地址
    [CRUD.HOOK.beforeRefresh]() {
      return false
    }, // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
    }
  }
}
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
</style>
